package cn.lingyangwl.agile.misc.statistic.listener;

import cn.lingyangwl.agile.misc.statistic.constant.*;
import cn.lingyangwl.agile.misc.statistic.model.*;
import cn.lingyangwl.agile.misc.statistic.service.*;
import cn.lingyangwl.agile.model.module.tenant.*;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 统计监听者
 * @author shenguangyang
 */
@Slf4j
@Component
@RabbitListener(bindings = {
        @QueueBinding(
                value = @Queue(value = StatisticCons.QUEUE_DAYS, durable = "true"), key = StatisticCons.QUEUE_DAYS,
                exchange = @Exchange(value = StatisticCons.EXCHANGE, type = ExchangeTypes.TOPIC))
})
public class DayDimStaticListener {
    @Resource
    private StatAnalyzeService analyzeService;

    @RabbitHandler
    public void onMessage(@Payload String data, Channel channel, Message message) throws Exception {
        try {
            log.info("listener statistic, msg: {}", data);
            DayDimStatReq statReq = DayDimStatReq.parse(data, DayDimStatReq.class);
            // 不统计不能识别的租户
            if (TenantContext.EMPTY_TENANT_ID.equals(statReq.getTenantId())) {
                return;
            }
            TenantContext.get().setTenantId(statReq.getTenantId());
            TenantContext.get().setMainTenantId(statReq.getMainTenantId());
            analyzeService.doStatistic(statReq);
        } catch (Exception e) {
            log.error("statistic fail, msg: {}, error: ", data, e);
        } finally {
            TenantContext.clear();
        }
    }
}
